package com.yonyou.state.core;

import com.yonyou.state.core.annotation.SOOperator;
import com.yonyou.state.core.annotation.SOProcessor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 状态机前置激活类,在spring中扫描配置此类 <br/>
 * 使用自定义注解标记对应的状态处理器和后置处理器并在初始化操作中完成对应处理器的初始化。
 * @author lidwt
 * @date 2021/10/31 15:30
 **/
@Component
public class Initialization implements BeanPostProcessor {

    @Resource
    SOStateManager manager;

    @Nullable
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof AbstractSOOperator && bean.getClass().isAnnotationPresent(SOOperator.class) ) {
            AbstractSOOperator orderState = (AbstractSOOperator) bean;
            manager.soOperatorMaps.put(orderState.getStatus(), orderState);
        }
        if (bean instanceof AbstractSOProcessor && bean.getClass().isAnnotationPresent(SOProcessor.class) ) {
            AbstractSOProcessor orderProcessor = (AbstractSOProcessor) bean;
            manager.soProcessorMaps.put(orderProcessor.getStatus(), orderProcessor);
        }
        return bean;
    }
}
